package com.wufun.overseas.main.activity;

import android.animation.ValueAnimator;
import android.bluetooth.BluetoothAdapter;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.animation.Interpolator;

import com.papa.controller.core.ControllerListener;
import com.papa.controller.core.ControllerManager;
import com.papa.controller.core.ControllerMonitor;
import com.papa.controller.core.PadKeyEvent;
import com.papa.controller.core.PadMotionEvent;
import com.papa.controller.core.PadStateEvent;
import com.wufun.baselibrary.base.BaseAppCompatActivity;
import com.wufun.overseas.joystick.EaseBreathInterpolator;
import com.wufun.overseas.joystick.map.BlackListManager;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xiet on 2016/11/17.
 */

public class HandShankBaseActivity extends BaseAppCompatActivity implements ControllerListener {

    private boolean spp4CheckInfo;

    public void setSpp4CheckInfo(boolean spp4CheckInfo) {
        this.spp4CheckInfo = spp4CheckInfo;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        startMonitor();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopMonitor();
    }

    //region HID输入监听
    public boolean dispatchKeyEvent(KeyEvent event) {
        boolean consumed = false;
        if (mControllerMonitor != null) {
            consumed |= mControllerMonitor.dispatchKeyEvent(event);
        }
        return consumed | super.dispatchKeyEvent(event);
    }

    public boolean dispatchGenericMotionEvent(MotionEvent event) {
        boolean consumed = false;
        if (mControllerMonitor != null) {
            consumed |= mControllerMonitor.dispatchGenericMotionEvent(event);
        }
        return consumed | super.dispatchGenericMotionEvent(event);
    }
    //endregion

    //region SPP输入监听
    ControllerMonitor mControllerMonitor;

    protected boolean isBlueEnabled() {
        BluetoothAdapter blueadapter = BluetoothAdapter.getDefaultAdapter();
        return blueadapter != null && blueadapter.isEnabled();
    }

    void startMonitor() {
        try {
            //event listener
            if (mControllerMonitor == null) {
                mControllerMonitor = new ControllerMonitor(this);
            }

            if (mControllerMonitor != null) {
                mControllerMonitor.setListener(this, new Handler());
                //connect listener
                setControllerDeviceListener();

                mControllerMonitor.setSpp4CheckInfo(spp4CheckInfo);

                mControllerMonitor.startMonitor();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void stopMonitor() {
        if (mControllerMonitor != null) {
            mControllerMonitor.stopMonitor();
        }
    }

    //region ControllerDeviceListener device connect state
    void setControllerDeviceListener() {
        if (mControllerMonitor != null) {
            //connect listener
            mControllerMonitor.setControllerDeviceListener(new ControllerManager.ControllerDeviceListener() {
                @Override
                public void onControllerDeviceAdded(ControllerManager.ControllerDevice device) {
//                    int count = mControllerMonitor.getControllerDeviceCount();
//                    if (count == 1) {
//                        log("all devices are connected", "手柄已连接");
//                    }
                    onControllerDeviceChanged(1, mControllerMonitor.getControllerDevices());
                }

                @Override
                public void onControllerDeviceRemoved(ControllerManager.ControllerDevice device) {
//                    int count = mControllerMonitor.getControllerDeviceCount();
//                    if (count == 0) {
//                        log("all devices are disconnected", "手柄已断开");
//                    }
                    onControllerDeviceChanged(0, mControllerMonitor.getControllerDevices());
                }
            });
        }
    }
    //endregion

    //region 手柄震动
    public void startVibrate() {
        long          duration     = 1200;
        Interpolator  interpolator = new EaseBreathInterpolator();
        ValueAnimator anim         = ValueAnimator.ofInt(0, 0xFF);
        anim.setDuration(duration);
        anim.setInterpolator(interpolator);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Integer v = (Integer) animation.getAnimatedValue();
                setVibrate(v, v);
            }
        });
        anim.start();
    }

    public void setVibrate(int intensityL, int intensityR) {
        if (mControllerMonitor != null)
            mControllerMonitor.setVibrate(intensityL, intensityR);
    }
    //endregion

    //region ControllerListener
    @Override
    public void onKeyDown(int keyCode, PadKeyEvent padKeyEvent) {
        onKeyEvent(keyCode, padKeyEvent);
    }

    @Override
    public void onKeyUp(int keyCode, PadKeyEvent padKeyEvent) {
        onKeyEvent(keyCode, padKeyEvent);
    }

    @Override
    public void onKeyPressure(int keyCode, float pressure, PadKeyEvent padKeyEvent) {
        onKeyEvent(keyCode, padKeyEvent);
    }

    @Override
    public void onLeftStick(float x, float y, PadMotionEvent padMotionEvent) {
        onStickEvent(padMotionEvent);
    }

    @Override
    public void onRightStick(float x, float y, PadMotionEvent padMotionEvent) {
        onStickEvent(padMotionEvent);
    }

    @Override
    public void onStateEvent(PadStateEvent padStateEvent) {

    }
    //endregion

    //region KeyEvent Convert
    protected boolean onKeyEvent(int keyCode, PadKeyEvent event) {
        return false;
    }

    protected boolean onStickEvent(PadMotionEvent event) {
        return false;
    }

    KeyEvent getStickLeftXEvent(float direction, int action) {
        int code = direction < 0 ? KeyEvent.KEYCODE_DPAD_LEFT : direction > 0 ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_UNKNOWN;
        return new KeyEvent(action, code);
    }

    KeyEvent getStickLeftYEvent(float direction, int action) {
        int code = direction < 0 ? KeyEvent.KEYCODE_DPAD_UP : direction > 0 ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_UNKNOWN;
        return new KeyEvent(action, code);
    }

    KeyEvent padEvent2KeyEvent(PadKeyEvent event) {
        KeyEvent ret = null;

        int   keyCode   = event.getKeyCode();
        int   action    = event.getAction();
        float pressure  = event.getPressure();
        int   deviceId  = event.getDeviceId();
        long  eventTime = event.getEventTime();
        ret = new KeyEvent(action, keyCode);
        return ret;
    }
    //endregion

    //endregion

    public void onControllerDeviceChanged(int state, List<ControllerManager.ControllerDevice> controllerDevices) {

    }

    //region Blacklist
    protected int getValidDeviceCount(List<ControllerManager.ControllerDevice> list) {
        return getValidDevice(getValidDevice(list)).size();
    }

    protected List<ControllerManager.ControllerDevice> getValidDevice(List<ControllerManager.ControllerDevice> list) {
        List<ControllerManager.ControllerDevice> ret = new ArrayList<ControllerManager.ControllerDevice>();
        if (list == null || list.size() == 0) return ret;

        for (int i = 0; i < list.size(); i++) {
            String deviceName = list.get(i).getName();
            if (!inBlackList(deviceName)) {
                ret.add(list.get(i));
            }
        }
        return ret;
    }

    protected boolean inBlackList(String deviceName) {
        return BlackListManager.getInstance().isInBlackList(deviceName);
    }

    //endregion
}
